﻿using Account.Api.Dtos;
using Account.Api.Entitys;
using Account.Api.Services;
using Cyss.Core;
using Cyss.Core.Api;
using Cyss.Core.Repository;
using Cyss.Core.Repository.EF;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace Account.Api.Controllers
{

    /// <summary>
    /// 获取会员 Api 接口
    /// </summary>
    public class UserController : AccountBaseApiController
    {
        #region 初始化
        private readonly UserService _userService;
        private readonly UserRoleService _userRoleService;
        private readonly MenuService _menuService;
        private readonly DepartmentService _departmentService;
        private readonly RolePermissionService _rolePermissionService;
        private readonly PermissionService _permissionService;
        public UserController(UserService userService,
            UserRoleService userRoleService,
            MenuService menuService,
            DepartmentService departmentService,
            RolePermissionService rolePermissionService,
            PermissionService permissionService,
            IMessageContext message
            )
        {
            _userService = userService;
            _userRoleService = userRoleService;
            _menuService = menuService;
            _departmentService = departmentService;
            _rolePermissionService = rolePermissionService;
            _permissionService = permissionService;
        }
        #endregion

        #region 会员增删该查

        /// <summary>
        /// 获取会员记录
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<OperateResult<UserModel>> GetUserById(int Id)
        {

            var tokenHelper = IOCEngine.Resolve<ITokenHelper>();
            UserModel user = new UserModel();
            user.Name = "asdf";
            var asdf = tokenHelper.CreateToken(user);

            var stasf = tokenHelper.GetTokenUser<UserModel>(asdf.TokenStr);

            var entity = _userService.GetById(Id, true);

            return OperateResultContent<UserModel>(true, entity.ToModel<UserModel>());
        }

        /// <summary>
        /// 获取会员分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<OperateResult<UserListModel>> GetPageListUsers(UserSearchModel model)
        {
            var entitys = _userService.GetPageListUserModels(model);
            var userRoles = _userRoleService.GetModels(x => entitys.Select(s => s.Id).Contains(x.UserId));
            var viewModel = new UserListModel
            {
                Data = entitys.Select(model =>
               {
                   model.UserRoleIds = userRoles.Where(x => x.UserId == model.Id).Select(x => x.RoleId);
                   model.UserRoleNames = string.Join(",", userRoles.Where(x => x.UserId == model.Id).Select(x => x.RoleName));
                   return model;
               }),
                Total = entitys.TotalCount
            };
            return OperateResultContent(true, viewModel);
        }

        /// <summary>
        /// 创建会员
        /// </summary>
        /// <param name="model">会员model</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<OperateResult<int>> CreateUser(UserModel model)
        {
            using (var transaction = new LogicalTransaction())
            {
                try
                {
                    var entity = model.ToEntity<User>();
                    entity.CreateBy = CurrentAccountUser.Id;
                    entity.CreateDate = DateTime.Now;
                    entity.SetDefaultValue();
                    _userService.Insert(entity);
                    if (model.UserRoleIds != null)
                    {
                        _userRoleService.Delete(x => x.UserId == entity.Id);
                        _userRoleService.Insert(model.UserRoleIds.Select(x => new UserRole { UserId = entity.Id, RoleId = x, CreateDate = DateTime.Now, CreateBy = this.CurrentAccountUser.Id }));
                    }
                    transaction.Success();
                    return OperateResultContent(true, entity.Id, "");
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    transaction.Fail();
                    return OperateResultContent(false, 0, ex.Message);
                }
            }
        }


        /// <summary>
        /// 编辑会员
        /// </summary>
        /// <param name="model">用户model</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<OperateResult> EditUser(UserModel model)
        {
            var entity = _userService.GetById(model.Id);
            entity.Number = model.Number;
            entity.Name = model.Name;
            entity.Remarks = model.Remarks;
            entity.Birthday = model.Birthday;
            entity.CardID = model.CardID;
            entity.Sex = model.Sex;
            entity.Pwd = model.Pwd;
            entity.Grade = model.Grade;
            entity.No = model.No;
            entity.Nickname = model.Nickname;
            entity.Phone = model.Phone;
            entity.EmergencyContact = model.EmergencyContact;
            entity.EmergencyContact_Phone = model.EmergencyContact_Phone;
            entity.PortraitRoute = model.PortraitRoute;
            entity.PortraitRoutePictureId = model.PortraitRoutePictureId;
            entity.DeptId = model.DeptId;
            entity.UpdateBy = CurrentAccountUser.Id;
            entity.UpdateDate = DateTime.Now;
            entity.IsEnabled = model.IsEnabled;
            entity.FileId = model.FileId;
            entity.SetDefaultValue();
            if (model.UserRoleIds != null && model.UserRoleIds.Any())
            {
                _userRoleService.Delete(x => x.UserId == entity.Id);
                _userRoleService.Insert(model.UserRoleIds.Select(x => new UserRole { UserId = entity.Id, RoleId = x, CreateDate = DateTime.Now, CreateBy = this.CurrentAccountUser.Id }));
            }
            _userService.Update(entity);
            return OperateResultContent(true);
        }

        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<OperateResult> DeleteUser([FromBody] int Id)
        {
            if (Id <= 0)
            {
                return OperateResultContent(false, "参数验证失败");
            }
            _userService.Delete(Id);
            return OperateResultContent(true);
        }
        #endregion

        #region 用户验证

        [HttpPost]
        public OperateResult EdidUserPassword(EditPasswordModel model)
        {
            var IsSuccess = _userService.EdidUserPassword(model);
            return OperateResultContent(IsSuccess, MessageContext.GetMessage());
        }


        [HttpPost]
        public OperateResult<LoginReturnModel> Login(LoginModel loginModel)
        {
            var user = _userService.GetUser(loginModel.UserNo, loginModel.UserPwd);
            var model = user.ToModel<LoginReturnModel>();
            if (model != null)
            {
                var tokenHelper = IOCEngine.Resolve<ITokenHelper>();
                //var token = tokenHelper.CreateToken(user.Id.ToString(), user.Name);
                //model.Token = token;
                _userService.GenerateLoginReturnModel(model);
            }
            return OperateResultContent(true, model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public OperateResult<bool> ValiToken([FromBody] string token)
        {
            var tokenHelper = IOCEngine.Resolve<ITokenHelper>();
            if (tokenHelper.ValiToken(token))
            {
                return OperateResultContent(true, true);
            }
            return OperateResultContent(false, false);
        }


        [HttpPost]
        public OperateResult<LoginReturnModel> TokenLogin([FromBody] string token)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                return OperateResultContent<LoginReturnModel>(false, null);
            }
            var tokenHelper = IOCEngine.Resolve<ITokenHelper>();
            if (tokenHelper.ValiToken(token))
            {
                string userId = "";
                string userName = "";
                //tokenHelper.GetTokenUser(token, ref userId, ref userName);
                LoginReturnModel loginReturnModel = new LoginReturnModel();
                loginReturnModel.Id = int.Parse(userId);
                loginReturnModel.Name = userName;
                _userService.GenerateLoginReturnModel(loginReturnModel);
                return OperateResultContent(true, loginReturnModel);
            }
            return OperateResultContent<LoginReturnModel>(false, null);
        }
        #endregion
    }
}




